<?php

namespace App\Services;

use App\Models\FleaNotice;
use App\Models\Mini\FleaGoodsModel;
use App\Models\Mini\FleaMsgModel;
use Illuminate\Support\Facades\DB;

class FleaMsgService extends BaseService
{
    protected $user;

    public function __construct()
    {
        $this->user = auth('user')->user();
    }


    public function addFleaMsg($data): array
    {
        $user_id = $this->user['id'];
        $data['user_id'] = $user_id;
        $data['created_at'] = time();
        $goods_id = $data['goods_id'];
        //查询发布商品的用户是谁
        $goods_user_id = FleaGoodsModel::query()->where('id', $goods_id)->value('user_id');
        DB::beginTransaction();
        $flag = false;
        try {
            $result = FleaMsgModel::insert($data);
            //如果通知的人是登录的人，那就不用通知了
            if ($goods_user_id != $user_id) {
                //评论后添加通知
                $create = [
                    'type' => 2,  // 1收藏  2留言  3订单评论  4提现
                    'msg' => '给你的发布留言了',
                    'goods_id' => $goods_id, //邻里圈跳蚤市场商品ID
                    'user_id' => $goods_user_id, //被通知人ID
                    'user_from_id' => $this->user['id'] //来自谁的通知用户ID
                ];
                //记录通知
                FleaNotice::query()->create($create);
            }
            $flag = true;
            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            $flag = false;
        }

        return $result ? $this->format($flag) : $this->format_error($flag);
    }

    /**
     * 获取用户发布的闲置列表
     * @Notes
     * @return array
     * @author ypp
     * @date 2021/3/6
     * @time 11:13
     */
    public function getFealMsgListByUserId(): array
    {
        $result = FleaMsgModel::with('children')
            ->with('user_info')
            ->where(['pid'=>0,'goods_id'=>request()->goods_id])
            ->select()
            -> paginate(request()->per_page ?? 10)
            -> toArray();
        return $result ? $this->format($result) : $this->format_error('暂无数据');
    }



}
